// app.js
App({
  onLaunch() {
    // 展示本地存储能力
    const logs = wx.getStorageSync("logs") || [];
    logs.unshift(Date.now());
    wx.setStorageSync("logs", logs);

    // 登录
    wx.login({
      success: (res) => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
      },
    });

    // 初始化tabBar
    this.initTabBar();
  },

  onShow() {
    // 每次显示时检查用户身份并更新tabBar
    this.updateTabBar();
  },

  /**
   * 初始化tabBar
   */
  initTabBar() {
    // 默认tabBar配置（普通用户）
    this.defaultTabBar = [
      {
        pagePath: "pages/home/index",
        iconPath: "images/home.png",
        selectedIconPath: "images/home-active.png",
        text: "首页",
      },
      {
        pagePath: "pages/personalCenter/index",
        iconPath: "images/personalCenter.png",
        selectedIconPath: "images/personalCenter-active.png",
        text: "个人中心",
      },
    ];

    // 管理员tabBar配置
    this.adminTabBar = [
      {
        pagePath: "pages/home/index",
        iconPath: "images/home.png",
        selectedIconPath: "images/home-active.png",
        text: "首页",
      },
      {
        pagePath: "pages/appointmentManage/index",
        iconPath: "images/personalCenter.png",
        selectedIconPath: "images/personalCenter-active.png",
        text: "个人中心",
      },
    ];

    // 设置默认tabBar
    this.setTabBar(this.defaultTabBar);
  },

  /**
   * 更新tabBar
   */
  updateTabBar() {
    try {
      const userInfo = wx.getStorageSync("userInfo");
      const isAdmin =
        userInfo && (userInfo.isAdmin || userInfo.role === "admin");

      if (isAdmin) {
        this.setTabBar(this.adminTabBar);
      } else {
        this.setTabBar(this.defaultTabBar);
      }
    } catch (error) {
      // 出错时使用默认配置
      this.setTabBar(this.defaultTabBar);
    }
  },

  /**
   * 设置tabBar
   */
  setTabBar(tabBarList) {
    try {
      // 设置tabBar项目
      tabBarList.forEach((item, index) => {
        wx.setTabBarItem({
          index: index,
          text: item.text,
          iconPath: item.iconPath,
          selectedIconPath: item.selectedIconPath,
          pagePath: item.pagePath,
        });
      });

      // 隐藏多余的tabBar项目
      for (let i = tabBarList.length; i < 5; i++) {
        wx.hideTabBarRedDot({
          index: i,
        });
      }
    } catch (error) {
      // 设置tabBar失败
    }
  },

  globalData: {
    userInfo: null,
    baseURL: require("./config.js").baseURL,
    imageServerURL: require("./config.js").imageServerURL,
  },
});
